<template>
  <div class="admin-order-container">
    
    <!-- 筛选和搜索区域 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <div class="filter-row">
          <div class="filter-group">
            <label>搜索关键词:</label>
            <el-input 
              v-model="searchParams.keyword" 
              placeholder="订单号/发件人/收件人/电话" 
              clearable 
              style="width: 250px;"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            />
          </div>
          
          <div class="filter-group">
            <label>订单状态:</label>
            <el-select 
              v-model="searchParams.orderStatus" 
              placeholder="请选择状态" 
              clearable 
              style="width: 150px;"
              @change="handleSearch"
            >
              <el-option
                v-for="(status, key) in statusMap"
                :key="key"
                :label="status.text"
                                 :value="Number(key)"
              />
            </el-select>
          </div>

          <div class="filter-group">
            <label>创建时间:</label>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px;"
              @change="handleDateChange"
            />
          </div>

          <div class="filter-actions">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilters">重置</el-button>
            <el-button @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="table-header">
          <h3>订单列表</h3>
          <div class="table-actions">
            <el-tag type="info" size="small">
              共 {{ totalItems }} 条记录
            </el-tag>
          </div>
        </div>
      </template>

      <el-table 
        :data="orderList" 
        style="width: 100%" 
        v-loading="loading"
        row-key="deliveryOrderId"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="orderNumber" label="订单号" min-width="180" fixed="left">
          <template #default="scope">
            <el-button link type="primary" @click="viewOrderDetail(scope.row)">
              {{ scope.row.orderNumber }}
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" min-width="160" sortable="custom">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="发件信息" min-width="200">
          <template #default="scope">
            <div class="contact-info">
              <div class="name">{{ scope.row.senderName }}</div>
              <div class="phone">{{ scope.row.senderPhone }}</div>
              <div class="address">{{ truncateAddress(scope.row.senderAddress) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="收件信息" min-width="200">
          <template #default="scope">
            <div class="contact-info">
              <div class="name">{{ scope.row.receiverName }}</div>
              <div class="phone">{{ scope.row.receiverPhone }}</div>
              <div class="address">{{ truncateAddress(scope.row.receiverAddress) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="itemWeight" label="重量(kg)" min-width="100" align="center" />
        <el-table-column prop="totalFee" label="运费(元)" min-width="100" align="center">
          <template #default="scope">
            <span class="fee-amount">¥{{ scope.row.totalFee }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="orderStatus" label="订单状态" min-width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.orderStatus)" size="small">
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="delivererId" label="配送员" min-width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.delivererId">ID: {{ scope.row.delivererId }}</span>
            <el-tag v-else type="info" size="small">未分配</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" min-width="200" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button link type="primary" size="small" @click="viewOrderDetail(scope.row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button 
                link 
                type="warning" 
                size="small" 
                @click="updateOrderStatus(scope.row)"
                :disabled="scope.row.orderStatus >= 4"
              >
                <el-icon><Edit /></el-icon>
                状态
              </el-button>
              <el-button 
                link 
                type="danger" 
                size="small" 
                @click="deleteOrder(scope.row)"
                :disabled="scope.row.orderStatus !== 0 && scope.row.orderStatus !== 4"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情模态框 -->
    <OrderDetailModal
      v-model:visible="orderDetailVisible"
      :order-detail="selectedOrder"
      :is-admin="true"
      @close="handleDetailClose"
      @status-update="handleStatusUpdateFromDetail"
    />

    <!-- 状态更新对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新订单状态" width="500px">
      <el-form :model="statusForm" label-width="100px" ref="statusFormRef">
        <el-form-item label="订单号">
          <el-input :value="currentOrder?.orderNumber" disabled />
        </el-form-item>
        
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(currentOrder?.orderStatus || 0)">
            {{ getStatusText(currentOrder?.orderStatus || 0) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="新状态" required>
          <el-select v-model="statusForm.orderStatus" placeholder="请选择新状态">
            <el-option
              v-for="(status, key) in statusMap"
              :key="key"
              :label="status.text"
                             :value="Number(key)"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="statusForm.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入状态更新备注（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmUpdateStatus" 
            :loading="statusUpdating"
          >
            确认更新
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Edit, Delete } from '@element-plus/icons-vue'
import { adminApi, type ApiResponse, type AdminOrderListResponse, type OrderStatistics } from '@/api/settings'
import OrderDetailModal from './components/OrderDetailModal.vue'

const route = useRoute()

// 统计数据
const statistics = ref({
  totalOrders: 0,
  waitingPickup: 0,
  waitingShipment: 0,
  inTransit: 0,
  waitingDelivery: 0,
  completed: 0,
  todayOrders: 0,
  monthOrders: 0
})

// 搜索参数
const searchParams = reactive({
  keyword: '',
  orderStatus: undefined as number | undefined,
  startDate: '',
  endDate: ''
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 订单列表
const orderList = ref<any[]>([])
const loading = ref(false)
const totalItems = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 订单详情
const orderDetailVisible = ref(false)
const selectedOrder = ref<any>(null)

// 状态更新
const statusDialogVisible = ref(false)
const statusUpdating = ref(false)
const currentOrder = ref<any>(null)
const statusForm = reactive({
  orderStatus: undefined as number | undefined,
  remark: ''
})

// 状态映射
const statusMap = {
  0: { text: '待揽收', type: 'danger' },
  1: { text: '待发货', type: 'warning' },
  2: { text: '运输中', type: 'primary' },
  3: { text: '待签收', type: 'info' },
  4: { text: '已完成', type: 'success' }
}

// 获取状态文本
const getStatusText = (status: number): string => {
  return statusMap[status as keyof typeof statusMap]?.text || '未知状态'
}

// 获取状态类型
const getStatusType = (status: number): string => {
  return statusMap[status as keyof typeof statusMap]?.type || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime: string): string => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 截断地址
const truncateAddress = (address: string): string => {
  if (!address) return ''
  return address.length > 20 ? address.substring(0, 20) + '...' : address
}

// 获取订单统计
const fetchStatistics = async () => {
  try {
    const response = await adminApi.getOrderStatistics()
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams
    }
    
    const response = await adminApi.getAllOrders(params)
    console.log('管理员订单列表响应:', response)
    
    if (response.code === 200) {
      orderList.value = response.data.list || []
      totalItems.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchOrderList()
}

// 日期范围变化
const handleDateChange = (dates: [string, string] | null) => {
  if (dates) {
    searchParams.startDate = dates[0]
    searchParams.endDate = dates[1]
  } else {
    searchParams.startDate = ''
    searchParams.endDate = ''
  }
  handleSearch()
}

// 重置筛选
const resetFilters = () => {
  searchParams.keyword = ''
  searchParams.orderStatus = undefined
  searchParams.startDate = ''
  searchParams.endDate = ''
  dateRange.value = null
  currentPage.value = 1
  fetchOrderList()
}

// 刷新数据
const refreshData = async () => {
  await Promise.all([
    fetchStatistics(),
    fetchOrderList()
  ])
  ElMessage.success('数据刷新成功')
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchOrderList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchOrderList()
}

// 排序处理
const handleSortChange = (column: any) => {
  // 可以根据需要实现排序功能
  console.log('排序变化:', column)
}

// 查看订单详情
const viewOrderDetail = async (order: any) => {
  try {
    const response = await adminApi.getOrderDetail(order.deliveryOrderId)
    if (response.code === 200) {
      selectedOrder.value = response.data
      orderDetailVisible.value = true
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 更新订单状态
const updateOrderStatus = (order: any) => {
  currentOrder.value = order
  statusForm.orderStatus = undefined
  statusForm.remark = ''
  statusDialogVisible.value = true
}

// 确认更新状态
const confirmUpdateStatus = async () => {
  if (!statusForm.orderStatus && statusForm.orderStatus !== 0) {
    ElMessage.warning('请选择新状态')
    return
  }
  
  try {
    statusUpdating.value = true
    const response = await adminApi.updateOrderStatus(
      currentOrder.value.deliveryOrderId,
      statusForm.orderStatus,
      statusForm.remark
    )
    
    if (response.code === 200) {
      ElMessage.success('订单状态更新成功')
      statusDialogVisible.value = false
      await refreshData()
    } else {
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  } finally {
    statusUpdating.value = false
  }
}

// 删除订单
const deleteOrder = async (order: any) => {
  if (order.orderStatus !== 0 && order.orderStatus !== 4) {
    ElMessage.warning('只有待揽收和已完成的订单才能删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除订单 ${order.orderNumber} 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await adminApi.deleteOrder(order.deliveryOrderId)
    if (response.code === 200) {
      ElMessage.success('订单删除成功')
      await refreshData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
      ElMessage.error('删除订单失败')
    }
  }
}

// 详情模态框关闭
const handleDetailClose = () => {
  orderDetailVisible.value = false
  selectedOrder.value = null
}

// 从详情页更新状态
const handleStatusUpdateFromDetail = () => {
  orderDetailVisible.value = false
  refreshData()
}

// 组件挂载
onMounted(() => {
  // 检查URL查询参数中是否有搜索关键词
  const searchKeyword = route.query.search as string
  if (searchKeyword) {
    searchParams.keyword = searchKeyword
    console.log('从URL获取搜索关键词:', searchKeyword)
  }
  
  refreshData()
})
</script>

<style scoped>
.admin-order-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 120px);
}

/* 统计面板样式 */
.statistics-panel {
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  font-size: 36px;
  margin-right: 16px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-top: 4px;
}

.stat-card.total { border-left: 4px solid #3498db; }
.stat-card.pending { border-left: 4px solid #e74c3c; }
.stat-card.shipping { border-left: 4px solid #f39c12; }
.stat-card.delivering { border-left: 4px solid #9b59b6; }
.stat-card.completed { border-left: 4px solid #27ae60; }
.stat-card.today { border-left: 4px solid #34495e; }

/* 筛选卡片样式 */
.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.filter-content {
  padding: 16px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-weight: 500;
  color: #606266;
  white-space: nowrap;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

/* 表格卡片样式 */
.table-card {
  border-radius: 12px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.table-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 表格内容样式 */
.contact-info {
  line-height: 1.4;
}

.contact-info .name {
  font-weight: 600;
  color: #2c3e50;
}

.contact-info .phone {
  color: #7f8c8d;
  font-size: 13px;
}

.contact-info .address {
  color: #95a5a6;
  font-size: 12px;
}

.fee-amount {
  font-weight: 600;
  color: #e67e22;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-actions {
    margin-left: 0;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .admin-order-container {
    padding: 16px;
  }
  
  .stat-content {
    padding: 16px;
  }
  
  .stat-icon {
    font-size: 28px;
  }
  
  .stat-value {
    font-size: 24px;
  }
}
</style>